#include "../includes/TaskConsumer.h"
#include "../includes/IPC.h"
#include "../includes/TaskManager.h"
#include <cstring>
#include <iostream>
#include <thread>
#include <atomic>
#include <chrono>

int main(){
    std::string socket_path = "/tmp/test_ipc.sock";
    IpcServer& server = IpcServer::getInstance(socket_path);
    TaskManager& task_manager = TaskManager::getInstance();
    TaskConsumer& task_consumer = TaskConsumer::getInstance();

    int client_fd = server.accept_conn();
    if (client_fd == -1) {
        std::cerr << "Accept failed" << std::endl;
        return 1;
    }

    std::atomic<bool> running(true);

    // --- 线程1: 接收客户端消息并解析任务 ---
    std::thread receiver_thread([&]() {
        std::string accumulated_data;

        while (running) { // 从消息缓冲中不断读取任务, 需要考虑tcp粘包问题
            char temp_buf[1024];
            int recv_size = server.receive_data(client_fd, sizeof(temp_buf), temp_buf);
            if(recv_size <= 0){
                if (recv_size < 0) {
                    std::cerr << "Receive error, receiver thread stopping." << std::endl;
                } else {
                    std::cout << "Client disconnected, receiver thread stopping." << std::endl;
                }
                running = false;
                break;
            }

            accumulated_data.append(temp_buf, recv_size);

            while (accumulated_data.length() >= sizeof(int32_t)) {
                int32_t task_len;
                std::memcpy(&task_len, accumulated_data.data(), sizeof(task_len));
                // ntohl if necessary

                if (task_len < 0 || task_len > 1024 * 1024) {
                     std::cerr << "Invalid task length received: " << task_len << std::endl;
                     running = false;
                     break;
                }

                if (accumulated_data.length() >= sizeof(task_len) + task_len) {
                    std::string new_task_str = accumulated_data.substr(sizeof(task_len), task_len);
                    task_manager.add_task(new_task_str);
                    accumulated_data.erase(0, sizeof(task_len) + task_len);
                } else {
                    break;
                }
            }
        }
        std::cout << "Receiver thread exiting." << std::endl;
    });

    // --- 线程2: 从任务队列取出任务并分发给线程池 ---
    std::thread dispatcher_thread([&]() {
        while (running) {
            if(task_consumer.idle_threads() > 0) {
                if(!task_manager.task_empty()){ // 检查队列是否非空
                    task_consumer.add_task();
                } else {
                    // 队列为空，短暂休眠，避免忙等待
                    std::this_thread::sleep_for(std::chrono::milliseconds(1));
                }
            } else {
                // 没有空闲线程，短暂休眠
                std::this_thread::sleep_for(std::chrono::milliseconds(1));
            }
        }
        std::cout << "Dispatcher thread exiting." << std::endl;
    });

    // --- 线程3: 从响应队列取出响应并发送给客户端 ---
    std::thread sender_thread([&]() {
        while (running) {
            if(!task_manager.resp_empty()){ // 检查队列是否非空
                std::string resp_str;
                task_manager.get_resp(resp_str);
                
                // --- 构建带长度前缀的发送数据 ---
                int32_t resp_len = resp_str.length(); // 获取响应字符串的长度
                
                // 1. 发送 4 字节长度 (注意字节序，如果客户端用 ntohl，则这里用 htonl)
                int32_t len_to_send = resp_len; // 如果客户端直接读取整数，使用主机字节序
                
                // 显式转换 const char* 到 const void*
                int len_send_size = server.send_data(client_fd, sizeof(len_to_send), 
                                                     static_cast<const void*>(reinterpret_cast<const char*>(&len_to_send)));
                if(len_send_size <= 0){
                    std::cerr << "Send response length error, code: " << len_send_size << ", sender thread stopping." << std::endl;
                    running = false;
                    break;
                }

                // 2. 发送响应内容
                // 显式转换 const char* 到 const void*
                int content_send_size = server.send_data(client_fd, resp_str.length(), 
                                                         static_cast<const void*>(resp_str.data()));
                if(content_send_size <= 0){
                    std::cerr << "Send response content error, code: " << content_send_size << ", sender thread stopping." << std::endl;
                    running = false;
                    break;
                }
                
            } else {
                // 队列为空，短暂休眠，避免忙等待
                std::this_thread::sleep_for(std::chrono::milliseconds(1));
            }
        }
        std::cout << "Sender thread exiting." << std::endl;
    });

    // 等待所有线程结束
    if (receiver_thread.joinable()) {
        receiver_thread.join();
    }
    if (dispatcher_thread.joinable()) {
        dispatcher_thread.join();
    }
    if (sender_thread.joinable()) {
        sender_thread.join();
    }

    std::cout << "All threads finished. Server shutting down." << std::endl;
    return 0;
}